# 竞赛service层
from flask import jsonify
from werkzeug.datastructures import FileStorage
import os
import pandas as pd
import dao.RaceDao as RaceDao
import vo.RaceVo as RaceVo
import utils.getByteType as getByteType
import utils.JudgeTool as JudgeTool


#  数据库获取竞赛列表
def service_race_getRaceList(status, category, raceCategory, search, uuid):
    result_dao = RaceDao.dao_race_getRaceList(status, category, raceCategory, search, uuid)
    result = RaceVo.vo_race_getRaceList(result_dao)
    return jsonify(result)


#  数据库获取竞赛详情
def service_race_detail(raceId, uuid):
    result_dao = RaceDao.dao_race_detail(raceId, uuid)
    result = RaceVo.vo_race_detail(result_dao)
    return jsonify(result)


#  数据库获取竞赛排名
def service_race_rank(raceId):
    result_dao = RaceDao.dao_race_rank(raceId)
    result = RaceVo.vo_race_rank(result_dao)
    return jsonify(result)


#  提交比赛文件
def service_race_submitFile(raceId, uuid, file):
    byteType = getByteType.getByteName(file)
    if byteType not in ('xls', 'xlsx', 'json', 'csv'):
        result = RaceVo.vo_race_default_fail()
        return jsonify(result)

    test_abs_url = '/root/view-master/app/static/race-test'
    test_url = os.path.join(test_abs_url, str(raceId) + '-' + str(uuid) + '.' + byteType)
    FileStorage(file).save(test_url)
    if not os.path.exists(test_url):
        result = RaceVo.vo_race_default_fail()
        return jsonify(result)

    ans_abs_url = '/root/view-master/app/static/race-ans'
    ans_url = os.path.join(ans_abs_url, str(raceId) + '.csv')
    if not os.path.exists(ans_url):
        result = RaceVo.vo_race_default_fail()
        return jsonify(result)

    if byteType in ('xls', 'xlsx'):
        test_df = pd.read_excel(test_url)
    elif byteType == 'json':
        test_df = pd.read_json(test_url)
    elif byteType == 'csv':
        test_df = pd.read_csv(test_url)
    else:
        return jsonify(RaceVo.vo_race_default_fail())

    ans_df = pd.read_csv(ans_url)

    score = JudgeTool.judge(test_df, ans_df)

    os.remove(test_url)

    result_dao = RaceDao.dao_race_submitFile(raceId, uuid, score)
    result = RaceVo.vo_race_submitFile(result_dao)
    return jsonify(result)
